<?php
namespace app\admin\controller;
use think\Request;
use think\Session;
use app\common\controller\Backend;
use app\common\model\ArticleModel;
use app\common\model\CategoryModel;

class Article extends Backend
{
	public function index(Request $request = null)
	{
  	$ArticleModel = new ArticleModel();
    $params = Request::instance()->get();
  	$list = $ArticleModel->getArticleList($params);

    //获取分类列表
    $categoryList = (new CategoryModel())->getAllCategory();
  	return view("index",[
  		'list' => $list,
      'categoryList' => $categoryList
  	]);
	}

	public function create(Request $request = null){
    if(Request::instance()->isPost()){
      $post = $request->post();
      $ArticleModel = new ArticleModel();
      // var_dump( $post );die();
      if($post['editor_type'] == 1){
        $post['markdown'] = $post['editormd-markdown-doc'];
        $post['content'] = $post['editormd-html-code'];
      }
      // var_dump( $post );die();
      $result = $ArticleModel->allowField(true)->validate(true)->save($post);
      if(false === $result){
        // 验证失败 输出错误信息
        $this->error($ArticleModel->getError());
      }else{
        $this->success("成功！");
      }
    }else{
    	$CategoryModel = new CategoryModel();
    	$category = $CategoryModel->getAllCategory();

      return view("create",['category'=>$category]);
    }
	}

   //更新页面
  public function update(){
    if(Request::instance()->isPost()){
      $post = Request::instance()->post();
      $ArticleModel = new ArticleModel();

      if($post['editor_type'] == 1){
        $post['markdown'] = $post['editormd-markdown-doc'];
        $post['content'] = $post['editormd-html-code'];
      }

      $result = $ArticleModel->allowField(true)->validate(true)->save($post,['id'=>$post['id']]);

      if(false === $result){
          // 验证失败 输出错误信息
          $this->error($ArticleModel->getError());
      }else{

        $this->success("成功！");
      }
    }else{
      $id = Request::instance()->param('id/d',0);
      $ArticleModel = new ArticleModel();
      $articleModel = $ArticleModel->getArticleById($id);

    	$CategoryModel = new CategoryModel();
    	$category = $CategoryModel->getAllCategory();

      return view("update",['articleModel'=> $articleModel,'category'=>$category]);
    }
  }

  /*删除*/
  public function deleteall(){

    $ArticleModel = new ArticleModel();
    if($ArticleModel->deleteall($_POST['id']) > 0){
      return json(['status'=>200,'msg'=>'成功']);
    }else{
      return json(['status'=>400,'msg'=>'失败']);
    }
  }
}